require 'digest/sha1'

class User < ActiveRecord::Base
  has_many :pages
  has_many :events
  has_many :projects
  
  validates_presence_of :nickname, :email, :full_name
  validates_uniqueness_of :nickname
  validates_uniqueness_of :email
  validates_format_of :email,
                      :with =>  %r{^[a-zA-Z0-9@\.]*}i,
                       :message => "Invalid Email"
  
  attr_accessor :password_confirmation
  validates_confirmation_of :password
  
  def validation
    errors.add_to_base("Missing password") if hashed_password.blank?
  end
  
  def password
    @password
  end
  
  def password=(pwd)
    @password = pwd
    create_new_salt
    self.hashed_password = User.encrypted_password(self.password, self.salt)
  end
  
  def self.authenticate(nickname, password)
    user = self.find_by_nickname(nickname)
    
    if user
      expected_password = encrypted_password(password, user.salt)
      
      if user.hashed_password != expected_password
        user = nil
      end
    end
    user
  end  
private
  
  def self.encrypted_password(password, salt)
    string_to_hash = password + "wibble" + salt
    Digest::SHA1.hexdigest(string_to_hash)
  end
  
  def create_new_salt
    self.salt = self.object_id.to_s + rand.to_s
  end
end
